package org.jenkinsci.plugins.p4scm.utils;

import java.util.Map;

import javax.annotation.Nonnull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jenkins.model.Jenkins;
import hudson.matrix.Axis;
import hudson.matrix.MatrixConfiguration;
import hudson.matrix.MatrixProject;
import hudson.model.ParameterValue;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.ParameterDefinition;
import hudson.model.ParametersDefinitionProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.EnvironmentVariablesNodeProperty;

public class JobSubstitutionHelper {
    
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(JobSubstitutionHelper.class);

    static void getDefaultSubstitutions(
            @Nonnull AbstractProject<?,?> project, 
            @Nonnull Map<String, String> subst) {
        
        subst.put("JOB_NAME", JobSubstitutionHelper.getSafeJobName(project));
        String rootUrl = Jenkins.getInstance().getRootUrl();
        if (rootUrl != null) {   
            subst.put("JOB_URL", rootUrl + project.getUrl());
        }
        
        for (NodeProperty<?> nodeProperty : Jenkins.getInstance().getGlobalNodeProperties()) {
            if (nodeProperty instanceof EnvironmentVariablesNodeProperty) {
                subst.putAll(((EnvironmentVariablesNodeProperty) nodeProperty).getEnvVars());
            }
        }
        ParametersDefinitionProperty pdp = (ParametersDefinitionProperty) project.getProperty(hudson.model.ParametersDefinitionProperty.class);
        if (pdp != null) {
            for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
                try {
                    ParameterValue defaultValue = pd.getDefaultParameterValue();
                    if (defaultValue != null) {
                        String name = defaultValue.getName();
                        String value = defaultValue.createVariableResolver(null).resolve(name);
                        subst.put(name, value);
                    }
                } catch (Exception e) {
                    // Do nothing
                }
            }
        }
        
        // Handle Matrix Axes
        if (project instanceof MatrixConfiguration) {
            MatrixConfiguration matrixConfiguration = (MatrixConfiguration) project;
            subst.putAll(matrixConfiguration.getCombination());
        }
        if (project instanceof MatrixProject) {
            MatrixProject matrixProject = (MatrixProject) project;
            for (Axis axis : matrixProject.getAxes()) {
                subst.put(axis.getName(), axis.size() >0 ? axis.value(0) : "");
            }
        }
    }
    
    public static String getSafeJobName(@Nonnull AbstractBuild<?,?> build) {
        return getSafeJobName(build.getProject());
    }

    public static String getSafeJobName(@Nonnull AbstractProject<?,?> project) {
        return project.getFullName().replace('/', '-').replace('=', '-').replace(',', '-');
    }
}
